import {messages} from "share/common";
import React, { Component, PropTypes } from "react"
import {Input, Icon, Popover} from 'antd'
import DepartmentDialog from "components/template/department/department-dialog"

class Department extends Component {

  state = {
    value: this.props.value || [],
    visible: false
  };

  componentWillReceiveProps = nextProps => {
    this.setState({ value: nextProps.value || [] })
  };

  handleFocus = () => {
    this.refs.departmentRef.focus();
    this.setState({ visible: true });
  };

  handleOnOk = value => {
    this.setState({ value, visible: false }, this.onChange);
  };

  onChange = () => {
    const { value } = this.state, { onChange } = this.props;
    if (onChange) {
      onChange(value);
    }
  };

  render() {
    const { value, visible } = this.state;
    const { isNeedCompany, needEntity, showCompany, parser, single, hideSubDepartment } = this.props;
    let popVisible = !value.length ? { visible: false } : {};
    return (
      <div>
        <Popover
          placement="topLeft"
          content={value.map(item => item.title || item.name || item.path).join(',')}
          {...popVisible}
        >
          <Input
            suffix={<Icon
              type={'close-circle'}
              onClick={() => this.setState({ value: [] }, this.onChange)}
              className='close-tag'
              style={value.length ? {} : { display: 'none' }}
            />}
            className={'hover-input'}
            value={value.map(item => item.title || item.name || item.path).join(',')}
            onFocus={this.handleFocus}
            placeholder={messages('common-1.key52')/*请选择temp*/}
          />
        </Popover>
        <DepartmentDialog
          visible={visible}
          onCancel={() => this.setState({ visible: false })}
          value={value}
          parser={parser}
          single={single}
          hideSubDepartment={hideSubDepartment}
          needEntity={needEntity}
          isNeedCompany={isNeedCompany}
          showCompany={showCompany}
          onOk={this.handleOnOk}
        />
        <div>
          <input
            ref="departmentRef"
            style={{ opacity: 0, position: 'fixed', width: 0, height: 0, zIndex: -1 }}
          />
        </div>
      </div>
    )
  }

  static propTypes = {
    isNeedCompany: PropTypes.bool,
    needEntity: PropTypes.bool,
    showCompany: PropTypes.bool,
    parser: PropTypes.func,
    hideSubDepartment: PropTypes.bool,
    single: PropTypes.bool
  };

  static defaultProps = {
    isNeedCompany: false,
    needEntity: false,
    showCompany: false,
    hideSubDepartment: false,
    single: false,
    parser: item => ({
      id: item.id,
      departmentOID: item.departmentOID,
      departmentCode: item.departmentCode,
      title: item.custDeptNumber ? `${item.custDeptNumber} ${item.name}` : item.name,
      path: item.path
    })
  }

}

export default Department
